class QuestionsController < ApplicationController
  # GET /questions
  # GET /questions.xml

  before_filter :current_user_est_admin, :except => [:voter, :vote_oui, :vote_non]
  before_filter :vote_du_jour, :only => [:vote_oui, :vote_non]

  def current_user_est_admin
    unless @template.signed_in? && @template.user_est_admin
      flash[:error] = "Vous devez être connecté en tant qu'administrateur pour accéder à cette page."
      begin
        redirect_to :back
      rescue ActionController::RedirectBackError
        redirect_to root_path
      end
    end
  end

  def vote_du_jour
    @question = Question.find(params[:id])
    unless @question.dateAffichage.eql?(Date.today)
      flash[:error] = "Vous ne pouvez voter que pour le vote du jour"
      begin
        redirect_to :back
      rescue
        redirect_to root_path
      end
    end
  end

  def index
    @questions = Question.all

    respond_to do |format|
      format.html # index.html.erb
    end
  end

  # GET /questions/new
  # GET /questions/new.xml
  def new
    @question = Question.new
    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # GET /questions/1/edit
  def edit
    @question = Question.find(params[:id])
  end

  # POST /questions
  # POST /questions.xml
  def create
    params[:question][:admin] = @template.current_user.compte
    params[:question][:oui] = 0
    params[:question][:non] = 0
    @question = Question.new(params[:question])

    respond_to do |format|
      if @question.save
        flash[:notice] = 'La question a été créée avec succès.'
        format.html { redirect_to questions_path }
      else
        format.html { render :action => "new" }
      end
    end
  end

  # PUT /questions/1
  # PUT /questions/1.xml
  def update
    @question = Question.find(params[:id])

    respond_to do |format|
      if @question.update_attributes(params[:question])
        flash[:notice] = 'la question a bien été mise à jour.'
        format.html { redirect_to questions_path }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  # DELETE /questions/1
  # DELETE /questions/1.xml
  def destroy
    @question = Question.find(params[:id])
    @question.destroy

    respond_to do |format|
      format.html { redirect_to(questions_url) }
    end
  end

  def voter
    if params[:reponse][:vote].eql?("oui")
      vote_oui
    else
      vote_non
    end
    session[:vote] = "voté"
  end

  def vote_oui
    @question = Question.find(params[:id])
    @question.update_attribute('oui', @question.oui+1)
    respond_to do |requete|
      flash[:notice] = "Merci pour le vote"
      requete.html { redirect_to root_path }
    end
  end

  def vote_non
    @question = Question.find(params[:id])
    @question.update_attribute('non', @question.non+1)
    respond_to do |requete|
      flash[:notice] = "Merci pour le vote"
      requete.html { redirect_to root_path }
    end
  end
end
